﻿/*
    框架mui 包含的js功能
    功能都包涵：选项卡、下拉面板，下拉菜单
*/

//选项卡
; (function ($, window) {
    $.fn.extend({
        muiTabs: function () {
            this.each(function () {
                var
                $this = $(this),
                $tabToggle = $this.find(".tabs-hd li a"),
                $tabBody = $this.find(".tabs-panel");
                $tabToggle.on("click", function (e) {
                    var
                            $that = $(this),
                            $ind = $that.parent().index();

                    $this.find(".tabs-hd a").removeClass("active");
                    $that.addClass("active");

                    $this.find(".tabs-panel").removeClass("active");
                    $this.find(".tabs-panel").eq($ind).addClass("active");

                    e.preventDefault();
                });
            });
        }
    });
})(jQuery, window);

//滚动监听侧边栏
(function () {
    var _sidenav = $("#sidenav");
    if (_sidenav.length !== 0) {
        var position = _sidenav.find("ul").offset();
        var t = position.top;
        $("body")
        .add($(window))
        .bind("scroll", function () {
            var st = $(document).scrollTop();
            if (st >= t) {
                _sidenav.find("ul").css({ "position": "fixed", "top": "20px", "left": "30px" });
            } else {
                _sidenav.find("ul").css({ "position": "absolute", "top": "0px", "left": "10px" });
            }
        });
    }
}());

//下拉
(function (window, $) {
    $.fn.extend({
        mdropdown: function () {
            this.each(function () {
                var
                        $this = $(this),
                        $toggle = $this.find(".dropdown-toggle"),
                        eventName = $this.attr("data-event");

                if (eventName == "hover") {
                    $toggle.bind("mouseenter", function () {
                        if (!$this.hasClass("dropdown-open")) {
                            $this.addClass("dropdown-open");
                        }
                    });

                    $this.bind("mouseleave", function () {
                        if (window.dropTimeOut) clearTimeout(window.dropTimeOut);
                        window.dropTimeOut = window.setTimeout(function () {
                            $this.removeClass("dropdown-open");
                        }, 1000);
                    });

                    $this.bind("mousemove", function () {
                        if (window.dropTimeOut) clearTimeout(window.dropTimeOut);
                    });
                } else {

                    $toggle.bind("click", function (e) {
                        if ($this.hasClass("dropdown-open")) {
                            $this.removeClass("dropdown-open");
                        } else {
                            $this.addClass("dropdown-open");
                        }
                        e.stopPropagation();
                        e.preventDefault();
                    });

                    $(document).bind("click", function () {
                        $this.removeClass("dropdown-open");
                    });

                }


            });
            return this;
        }
    });

    if ($(".mui-dropdown").length > 0) {
        $(".mui-dropdown").mdropdown();
    }
})(window, jQuery);

//表格过滤展开
(function () {
    $.fn.extend({
        filter: function () {
            this.each(function () {
                var
                        $this = $(this),
                        $btn = $(this).find(".btn-link");
                $btn.on("click", function () {
                    var $that = $(this);
                    if ($that.hasClass("selected")) {
                        $that.removeClass("selected");
                        $this.find(".form-inline").hide();
                        $this.find(".form-inline:eq(0)").show();
                    } else {
                        $that.addClass("selected");
                        $this.find(".form-inline").show()
                    }

                });

            })
            return this;
        }
    });
}());


//过滤传值
(function (window, $) {
    $.fn.extend({
        filterTable: function () {
            this.each(function () {
                var
                        $this = $(this),
                        $dom = $this.find("[data-type]"),
                        $btn = $this.find(".btn-filter");

                //点击搜索
                $btn.on("click", function () {
                    var robj = createfilterobj($this);
                    if ($.isEmptyObject(robj)) return false;
                    if ($(".tablemvc").length > 0 && $(".tablemvc").attr("data-src") != undefined) {
                        var $src = $(".tablemvc").attr("data-src");
                        $.ajax({
                            url: $src,
                            type: "GET",
                            data: robj,
                            beforeSend: function () {
                                if ($(".load-panel").length > 0) {
                                    $(".load-panel").show();
                                }
                            },
                            success: function () {
                                var data = arguments[0];

                                if (!data || data == undefined) return;
                                var result = eval("(" + data + ")");

                                var source = $("#table-template").html();
                                var template = Handlebars.compile(source);
                                var tableHtml = template(result[0].data);
                                $this.find("tbody").html(tableHtml);

                                if ($(".load-panel").length > 0) {
                                    $(".load-panel").hide();
                                }

                                if ($(".page-pagination").length > 0) {
                                    $(".page-pagination").pager({
                                        pNum: result[0].pageNum,
                                        pIndex: result[0].pageIndex,
                                        num: result[0].number,
                                        tNum: result[0].totalNumber
                                    });
                                }

                                //点击删除
                                if ($this.find(".mui-del").length > 0) {
                                    $this.find(".mui-del").one("click", function () {
                                        var
                                                $that = $(this),
                                                $par = $that.parents("tr");
                                        $par.remove();
                                        if ($this.find("tr").length < 10) {
                                            $(".tablemvc").filltable(curNum);
                                        }
                                    });
                                }
                            },
                            error: function (msg) {
                                alert("获取数据报错：" + msg);
                            }
                        });
                    }
                });

            });

            function createfilterobj($dom) {
                var $result = {};
                $dom.find("[data-name]").each(function () {
                    var
                            $this = $(this),
                            $name = $this.attr("data-name"),
                            $tagName = $this.get(0).tagName;

                    switch ($tagName) {
                        case "INPUT":
                            if ($this.attr("type") == "text") {
                                if ($this.val() != "") {
                                    $result[$name] = $this.val();
                                }
                            } else if ($this.attr("type") == "checkbox" || $this.attr("type") == "radio") {
                                if ($this.get(0).checked) {
                                    $result[$name] = $this.attr("id");
                                }
                            }
                            break;
                        case "SELECT":
                            if ($this.find("option:selected").attr("id") != undefined) {
                                $result[$name] = $this.find("option:selected").attr("id");
                            }
                            break;
                    }
                });
                return $result;
            }

            return this;
        }
    });

    if ($(".page-filter").length > 0) {
        $(".page-filter").filterTable();
    }

})(window, jQuery);

//表格全选，反选
(function () {
    $.fn.extend({
        checkall: function () {
            this.each(function () {
                var
                        $this = $(this),
                        $checkall = $("#checkAll");
                //全选和反选
                $checkall.on("click", function () {
                    $this.find(".checkbox").prop("checked", this.checked);
                    if (this.checked) {
                        $this.find(".checkbox").parents("tr").addClass("rselected");
                    } else {
                        $this.find(".checkbox").parents("tr").removeClass("rselected");
                    }
                });

                $this.delegate(".checkbox", "click", function () {
                    if (this.checked) {
                        $(this).parents("tr").addClass("rselected");
                    } else {
                        $(this).parents("tr").removeClass("rselected");
                    }

                    $this.find(".checkbox").each(function () {
                        var $that = $(this);
                        (function ($th) {
                            if ($th.prop("checked")) {
                                $checkall.prop("checked", true);
                            } else {
                                $checkall.prop("checked", false);
                            }
                        })($that);
                    });
                });

            });
            return this;
        }
    });
}());

//回到顶部
(function () {
    $.fn.extend({
        returnTop: function () {
            this.each(function () {
                var $this = $(this);
                var $elem = $this.find("a:first");

                $elem.bind("click", function () {
                    $("body,html").animate({ scrollTop: 0 }, 150);
                });

                $("body")
                .add($(window))
                .bind("scroll", function () {
                    var st = $(document).scrollTop();
                    (st > 100) ? $this.fadeIn(500) : $this.fadeOut(500);
                });
            });
            return this;
        }
    });
}());

//滚动监听
; (function ($, window, document, undefined) {
    $.fn.extend({
        scrollspy: function (options) {

            var defaults = {
                min: 0,
                max: 0,
                mode: 'vertical',
                namespace: 'scrollspy',
                buffer: 0,
                container: window,
                onEnter: options.onEnter ? options.onEnter : [],
                onLeave: options.onLeave ? options.onLeave : [],
                onTick: options.onTick ? options.onTick : []
            }

            var options = $.extend({}, defaults, options);

            return this.each(function (i) {

                var element = this;
                var o = options;
                var $container = $(o.container);
                var mode = o.mode;
                var buffer = o.buffer;
                var enters = leaves = 0;
                var inside = false;

                /* add listener to container */
                $container.bind('scroll.' + o.namespace, function (e) {
                    var position = { top: $(this).scrollTop(), left: $(this).scrollLeft() };
                    var xy = (mode == 'vertical') ? position.top + buffer : position.left + buffer;
                    var max = o.max;
                    var min = o.min;

                    /* fix max */
                    if ($.isFunction(o.max)) {
                        max = o.max();
                    }

                    /* fix max */
                    if ($.isFunction(o.min)) {
                        min = o.min();
                    }

                    if (max == 0) {
                        max = (mode == 'vertical') ? $container.height() : $container.outerWidth() + $(element).outerWidth();
                    }

                    /* if we have reached the minimum bound but are below the max ... */
                    if (xy >= min && xy <= max) {
                        /* trigger enter event */
                        if (!inside) {
                            inside = true;
                            enters++;

                            /* fire enter event */
                            $(element).trigger('scrollEnter', { position: position })
                            if ($.isFunction(o.onEnter)) {
                                o.onEnter(element, position);
                            }

                        }

                        /* trigger tick event */
                        $(element).trigger('scrollTick', { position: position, inside: inside, enters: enters, leaves: leaves })
                        if ($.isFunction(o.onTick)) {
                            o.onTick(element, position, inside, enters, leaves);
                        }
                    } else {

                        if (inside) {
                            inside = false;
                            leaves++;
                            /* trigger leave event */
                            $(element).trigger('scrollLeave', { position: position, leaves: leaves })

                            if ($.isFunction(o.onLeave)) {
                                o.onLeave(element, position);
                            }
                        }
                    }
                });

            });
        }
    });
})(jQuery, window, document, undefined);

//填充表格数据
; (function () {
    $.fn.extend({
        filltable: function (opt) {
            this.each(function () {
                var
                        $this = $(this),
                        $src = $this.attr("data-src");

                if (opt == undefined) opt = 1;

                $.ajax({
                    url: $src,
                    type: "GET",
                    data: { pageIndex: opt },
                    num: opt,
                    beforeSend: function () {
                        if ($(".load-panel").length > 0) {
                            $(".load-panel").show();
                        }
                    },
                    success: function () {
                        var
                                data = arguments[0],
                                curNum = this.num;
                        if (!data || data == undefined) return;
                        var result = eval("(" + data + ")");

                        var source = $("#table-template").html();
                        var template = Handlebars.compile(source);
                        var tableHtml = template(result[0].data);
                        $this.find("tbody").html(tableHtml);

                        if ($(".load-panel").length > 0) {
                            $(".load-panel").hide();
                        }

                        if ($(".page-pagination").length > 0) {
                            $(".page-pagination").pager({
                                pNum: result[0].pageNum,
                                pIndex: curNum,
                                num: result[0].number,
                                tNum: result[0].totalNumber
                            });
                        }

                        //点击删除
                        if ($this.find(".mui-del").length > 0) {
                            $this.find(".mui-del").one("click", function () {
                                var
                                        $that = $(this),
                                        $par = $that.parents("tr");
                                $par.remove();
                                if ($this.find("tr").length < 10) {
                                    $(".tablemvc").filltable(curNum);
                                }
                            });
                        }
                    },
                    error: function () { }
                })
            });
            return this;
        }
    });
}());

//分页翻页
; (function () {
    $.fn.extend({
        pager: function (opt) {
            this.each(function () {
                var
                        $this = $(this),
                        $num = $this.find("a"),
                        $src = $(".tablemvc").length ? $(".tablemvc").attr("data-src") : null;
                //创建分页HTML
                var phtml = createPager(opt);
                $this.html(phtml);

                //点击分页
                $this.find("a").one("click", function () {
                    var
                            $that = $(this),
                            $par = $that.parent(),
                            $selectedInd = $this.find("li.active a").attr("data-num"),
                            $dataNum = null;

                    if ($par.hasClass("disabled") || $par.hasClass("active")) {
                        return false;
                    }
                    else if ($par.hasClass("next")) {
                        $dataNum = $selectedInd * 1 + 1;
                    } else if ($par.hasClass("prev")) {
                        $dataNum = $selectedInd * 1 - 1;
                    } else {
                        $dataNum = $that.attr("data-num");
                    }

                    if ($(".tablemvc").length > 0) {
                        $(".tablemvc").filltable($dataNum);
                    }
                });
            });

            function createPager(paramsObj) {
                var
                        pNum = parseInt(paramsObj.pNum),
                        pIndex = parseInt(paramsObj.pIndex),
                        num = parseInt(paramsObj.num),
                        tnum = parseInt(paramsObj.tNum),
                        rhtml = "";

                if (pNum === 0) {
                    return "";
                };

                rhtml += '<div class="paginfo pull-left">当前第<b>' + pIndex + '</b>/<b>' + pNum + '</b>页 共<b>' + tnum + '</b>条记录 每页<b>' + num + '</b>条&nbsp;</div>';
                if (pIndex > 1) {
                    rhtml += '<ul><li class="prev"><a  title="上一页" href="javascript:void(0);">← Previous</a></li>';
                }
                else {
                    rhtml += '<ul><li class="prev disabled"><a   title="上一页" href="#">← Previous</a></li>';
                }


                //创建ul
                if (pNum > 0 && pNum <= 8) { //小于9
                    for (var i = 1; i <= pNum; i++) {

                        if (i == pIndex) {
                            rhtml += '<li class="active"><a title="' + pIndex + '" href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                        } else {
                            rhtml += '<li><a href="javascript:void(0);" title="' + i + '" data-num="' + i + '">' + i + '</a></li>';
                        }
                    }

                    if (pNum != 1 && pNum != pIndex) {
                        rhtml += '<li class="next"><a title="下一页" href="javascript:void(0);">Next →</a></li></ul>';
                    }
                    else {
                        rhtml += '<li class="next disabled"><a  title="下一页"  href="javascript:void(0);">Next →</a></li></ul>';
                    }
                }
                else if (pNum > 8 && pIndex < 5) { //大于8出现...

                    for (var i = 1; i <= pNum; i++) {

                        if (i == pIndex) {
                            rhtml += '<li class="active"><a title="' + pIndex + '" href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                        } else {
                            rhtml += '<li><a href="javascript:void(0);" title="' + i + '" data-num="' + i + '">' + i + '</a></li>';
                        }

                        if (i > 7) {
                            if (pNum == 9) {
                                rhtml += '<li><a href="javascript:void(0);" title="' + pNum + '" data-num="' + pNum + '">' + pNum + '</a></li>';
                            } else {
                                rhtml += '<li><a href="javascript:void(0);" title="9" data-num="9">...</a></li>';
                                rhtml += '<li><a href="javascript:void(0);" title="' + pNum + '" data-num="' + pNum + '">' + pNum + '</a></li>';
                            }
                            break;
                        }
                    }

                    if (pNum != 1 && pNum != pIndex) {
                        rhtml += '<li class="next"><a href="javascript:void(0);">Next →</a></li></ul>';
                    }
                    else {
                        rhtml += '<li class="next disabled"><a href="javascript:void(0);">Next →</a></li></ul>';
                    }
                }
                else if (pNum >= 9 && pIndex >= 5) { //pNum大于9&&pIndex>=5

                    rhtml += '<li><a href="javascript:void(0);" data-num="1">1</a></li>';
                    if (pIndex > 7 && pNum > 9) {
                        rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 3) + '">...</a></li>';
                        if (pNum - pIndex > 2) {
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 2) + '">' + (pIndex * 1 - 2) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 1) + '">' + (pIndex * 1 - 1) + '</a></li>';
                            rhtml += '<li class="active"><a href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 + 1) + '">' + (pIndex * 1 + 1) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 + 2) + '">' + (pIndex * 1 + 2) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 + 3) + '">...</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + pNum + '">' + pNum + '</a></li>';
                        }
                        else if (pNum - pIndex == 2) {
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 3) + '">' + (pIndex * 1 - 3) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 2) + '">' + (pIndex * 1 - 2) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 1) + '">' + (pIndex * 1 - 1) + '</a></li>';
                            rhtml += '<li class="active"><a href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 + 1) + '">' + (pIndex * 1 + 1) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 + 2) + '">' + (pIndex * 1 + 2) + '</a></li>';
                        }
                        else if (pNum - pIndex == 1) {
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 4) + '">' + (pIndex * 1 - 4) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 3) + '">' + (pIndex * 1 - 3) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 2) + '">' + (pIndex * 1 - 2) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 1) + '">' + (pIndex * 1 - 1) + '</a></li>';
                            rhtml += '<li class="active"><a href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 + 1) + '">' + (pIndex * 1 + 1) + '</a></li>';
                        }
                        else {
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 5) + '">' + (pIndex * 1 - 5) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 4) + '">' + (pIndex * 1 - 4) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 3) + '">' + (pIndex * 1 - 3) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 2) + '">' + (pIndex * 1 - 2) + '</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pIndex * 1 - 1) + '">' + (pIndex * 1 - 1) + '</a></li>';
                            rhtml += '<li class="active"><a href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                        }
                    }
                    else {
                        rhtml += '<li><a href="javascript:void(0);" data-num="4">...</a></li>';
                        for (var i = 5; i <= 9; i++) {
                            if (i == pIndex) {
                                rhtml += '<li class="active"><a href="javascript:void(0);" data-num="' + pIndex + '">' + pIndex + '</a></li>';
                            } else {
                                rhtml += '<li><a href="javascript:void(0);" data-num="' + i + '">' + i + '</a></li>';
                            }
                        }
                        if (pNum > 9) {
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + (pNum * 1 - 1) + '">...</a></li>';
                            rhtml += '<li><a href="javascript:void(0);" data-num="' + pNum + '">' + pNum + '</a></li>';
                        }
                    }

                    if (pNum != pIndex) {
                        rhtml += '<li class="next"><a href="javascript:void(0);">Next →</a></li></ul>';
                    }
                    else {
                        rhtml += '<li class="next disabled"><a href="javascript:void(0);">Next →</a></li></ul>';
                    }
                }

                return rhtml;
            }

            return this;
        }
    });
}());

//表格操作事件
; (function (window, $) {
    $.fn.extend({
        tableopt: function () {
            this.each(function () {
                var
                        $this = $(this),
                        $delBtn = $this.find(".btn-del"),
                        $opttable = $(".table-check");

                if ($delBtn && $opttable.length > 0) {
                    $delBtn.bind("click", function () {
                        $opttable.find("tr.rselected").remove();
                        //这里需要通过ajax来删除
                    });
                };
            });
            return this;
        }
    });

})(window, jQuery);

//调用
(function () {
    if ($(".mui-tabs").length > 0) {
        $(".mui-tabs").muiTabs();
    }

    if ($(".page-filter").length > 0) {
        $(".page-filter").filter();
    }
    if ($(".table-check").length > 0) {
        $(".table-check").checkall();
    }
    if ($(".returnback").length > 0) {
        $(".returnback").returnTop();
    }

    if ($(".scrollspy").length > 0) {
        $(".scrollspy").each(function (i) {
            var $this = $(this);
            var
                    position = $this.position(),
                    sidenav = $("#sidenav");

            $this.scrollspy({
                min: position.top,
                max: position.top + $this.height(),
                onEnter: function (element, position) {
                    var id = $this.attr("id");
                    sidenav.find("li").removeClass("active");
                    sidenav.find("a[href=#" + id + "]").parent().addClass("active");
                },
                onLeave: function (element, position) {

                }
            });
        });
    }

    if ($(".tablemvc").length > 0) {
        $(".tablemvc").filltable("8");
    }

    if ($(".table-option").length > 0) {
        $(".table-option").tableopt();
    }
}());